import {Sequelize, Op} from 'sequelize';
import _ from 'lodash';

class BaseBusinessController extends BasicController {


    /**
     * 获取当前账号负责的楼宇
     * hz_account -> hz_account_region -> hz_building['region_id']
     * @param account_id
     * @returns {Promise<unknown|*|Array>}
     */
    async buildingIds(account_id){
        let r = []
        if(!account_id){
           return r;
        }

        let sql = `select b.id  from hz_account_region ar
                INNER JOIN hz_region r ON r.id = ar.region_id
                INNER JOIN hz_building b ON b.region_id = r.id
                WHERE ar.account_id = ${account_id}`

        let results =await db.sql(sql)

        for(let result of results){
            r.push(result.id)
        }

        return r;
    }

    /**
     * @param state
     * @returns {Promise<boolean>}
     */
    async isAdmin(state) {
        if (!state || !state.user) {
            return false
        }
        if (!state.user.id) {
            return false
        }

        let account = await this.modules('Account').where({id: state.user.id}).first()
        if (!account) {
            return false
        }

        if (!account.role_id) {
            return false
        }

        let role = await this.modules('Role').where({id: account.role_id}).first()
        if (!role) {
            return false
        }

        return role.is_admin === 1;
    }

    async isValidAccount(state){
        if(!state || !state.user){
            throw  new Error("未登陆")
        }
        let account = await this.modules('Account').where({id: state.user.id}).first()
        if (!account) {
            throw  new Error("账号已不存在")
        }
        if(account.is_disable === 1){
            throw  new Error("账号已被禁用")
        }
    }


    async findAccount(state){
        if(!state || !state.user){
            throw  new Error("未登陆")
        }
        let account = await this.modules('Account').where({id: state.user.id}).first()
        if (!account) {
            throw  new Error("账号已不存在")
        }
        if(account.is_disable === 1){
            throw  new Error("账号已被禁用")
        }
        return account;
    }

    /**
     * @param state
     * @returns {Promise<boolean>}
     */
    async isAdminAccount(id) {
        let account = await this.modules('Account').where({id}).first()
        if (!account) {
            throw new Error("account lost")
        }

        if (!account.role_id) {
            throw new Error("account role lost")
        }

        let role = await this.modules('Role').where({id: account.role_id}).first()
        if (!role) {
            return false
        }

        return role.is_admin === 1;
    }

    /**
     * 验证post id参数
     * @param POST
     * @private
     */
    _validatePostId(POST){
        if(!POST){
            throw new Error("param lost")
        }
        if(!POST['id']){
            throw new Error("id not exit")
        }
    }

    /**
     * 转换权限/目录树
     * @param permissions
     * @returns {[]}
     * @private
     */
    _parsePermissionTree(permissions){
        let setInParent = (menu) => {
            if (menu.pid === null) {
                return
            }
            let item = _.find(permissions, o => o.id === menu.pid);
            if (item) {
                if (item.menus) {
                    let e = _.find(item.menus, i => i.id === menu.id);
                    if (!e) {
                        item.menus.push(menu)
                    }
                } else {
                    item.menus = [menu]
                }
                setInParent(item)
            }
        }
        for (let menu of permissions) {
            setInParent(menu)
        }
        let result = []
        for (let menu of permissions) {
            if (menu.pid === null) {
                result.push(menu)
            }
        }
        return result
    }

    /**
     * 获取报告自身在内的所有子权限
     * @param permission
     * @returns {Promise<*[]|[]|Array>}
     * @private
     */
    async _getSubPermissionIds(permission){
        if(!permission){
            return []
        }

        if(permission.type === 2){
            return [permission.id]
        }else{
            let querySql = "SELECT t3.id FROM (SELECT t1.*,IF (FIND_IN_SET(pid ,@pids) > 0,@pids := CONCAT(@pids, ',', id),0) AS ischild FROM (SELECT t.id, t.pid, t. NAME FROM hz_permission AS t ORDER BY t.id ASC) t1,(SELECT @pids := :PID) t2) t3 WHERE ischild != '0'";
            let results = await db.sql(querySql, {PID: permission.id})

            let ids = []
            for(let result of results){
                ids.push(result.id)
            }

            ids.push(permission.id)
            /**
             * 获取子权限
             */
            return ids
        }
    }



    /**
     * 获取分页参数
     * @returns {{number: *, size: *}}
     * @private
     */
    _getPage(){
        let page = $_POST['page'];
        let number = page && page.number !== undefined ? page.number : 1;
        let size = page && page.size !== undefined ? page.size : 20;
        return {number, size}
    }

    /**
     * 验证角色是否存在
     * @param id
     * @returns {Promise<void>}
     * @private
     */
    async _validateRole(id){
        let product = await this.modules('Role').where({id}).first();
        if(!product){
            throw new Error("角色未找到")
        }
    }

    /**
     * 验证角色是否存在并返回
     * @param id
     * @returns {Promise<void>}
     * @private
     */
    async _findRole(id){
        let product = await this.modules('Role').where({id}).first();
        if(!product){
            throw new Error("角色未找到")
        }
        return product;
    }
    /**
     * 获取用户角色
     * @param {*} userId 
     * @returns 
     */
    async _findRoleByUser(state){
        let account = await this.modules('Account').where({id: state.user.id}).first()
        let product = await this.modules('Role').where({id:account.role_id}).first()
        if(!product){
            throw new Error("角色未找到")
        }
        return product;
    }
    /**
     * 验证账号是否存在
     * @param id
     * @returns {Promise<void>}
     * @private
     */
    async _validateAccount(id){
        let product = await this.modules('Account').where({id}).first();
        if(!product){
            throw new Error("账号未找到")
        }
    }

    /**
     * 验证账号是否存在并返回
     * @param id
     * @returns {Promise<*>}
     * @private
     */
    async _findAccount(id){
        let product = await this.modules('Account').where({id}).first();
        if(!product){
            throw new Error("账号未找到")
        }
        return product;
    }

    /**
     * 验证权限是否存在
     * @param id
     * @returns {Promise<void>}
     * @private
     */
    async _validatePermission(id){
        let product = await this.modules('Permission').where({id}).first();
        if(!product){
            throw new Error("权限未找到")
        }
    }

    /**
     * 验证权限是否存在并返回
     * @param id
     * @returns {Promise<*>}
     * @private
     */
    async _findPermission(id){
        let product = await this.modules('Permission').where({id}).first();
        if(!product){
            throw new Error("权限未找到")
        }
        return product;
    }


    /**
     * 根据账号ID获取所管辖的楼宇ID集合
     */
    async _getBuildingIdsByAccountId(id){
        if(!id){
            return []
        }
        let sql = "select ab.building_id as id from hz_account a LEFT JOIN hz_account_building ab ON ab.account_id = a.id WHERE a.is_disable = 0 AND a.id = :account_id"
        let ids = await db.sql(sql, {account_id: id})
        let result = []
        for(let data of ids){
            result.push(data.id)
        }
        return result;
    }

    /**
     * 获取账号权限
     * account_id => 权限code
     * @param id
     * @returns {Promise<unknown|*>}
     * @private
     */
    async _findAccountPermissions(id){
        let sql = "SELECT DISTINCT p.`code` from hz_account a \n" +
            "LEFT JOIN hz_role r ON r.id = a.role_id\n" +
            "LEFT JOIN hz_role_permission rp ON rp.role_id = r.id\n" +
            "LEFT JOIN hz_permission p ON p.id = rp.permission_id\n" +
            "WHERE a.is_disable = 0 AND a.id = :account_id";
        return await db.sql(sql, {account_id: id});
    }

    /**
     * 验证是否有该权限
     * account_id +code => true/false
     * @param id
     * @param code
     * @returns {Promise<void>}
     * @private
     */
    async _validatePermission(id, code){
        let sql = "select COUNT(1) as count from hz_account a \n" +
            "LEFT JOIN hz_role r ON r.id = a.role_id\n" +
            "LEFT JOIN hz_role_permission rp ON rp.role_id = r.id\n" +
            "LEFT JOIN hz_permission p ON p.id = rp.permission_id \n" +
            "WHERE a.is_disable = 0 AND a.id = :account_id AND p.code = :code";
        let result = await db.sql(sql, {account_id: id, code});
        return result[0].count
    }


    /**
     * 验证地区code是否正确
     * @param province
     * @param city
     * @param area
     * @param street
     * @returns {Promise<void>}
     * @private
     **/
    async _validateAddress(province, city, area, street){
        let provinceData = await this.modules('Area').where({level: ORG_LEVEL.PROVINCE, code: province}).first();
        if(!provinceData){
            throw  new Error("[省]信息错误");
        }
        let cityData = await this.modules('Area').where({level: ORG_LEVEL.CITY, code:city}).first();
        if(!cityData){
            throw  new Error("[市]信息错误");
        }
        let areaData = await this.modules('Area').where({level: ORG_LEVEL.AREA, code:area}).first();
        if(!areaData){
            throw  new Error("[区/县]信息错误");
        }
        let streetData = await this.modules('Area').where({level: ORG_LEVEL.TOWN, code:street}).first();
        if(!streetData){
            throw  new Error("[街道/乡镇]信息错误");
        }
    }

    /**
     * 根据地址地区code获取地区全路径
     * @param province
     * @param city
     * @param area
     * @param street
     * @param address
     * @returns {Promise.<*>}
     */
    async fullAddress(province, city, area, street, address){
        let sql = "SELECT GROUP_CONCAT(name SEPARATOR '') as name FROM hz_area where code IN ("
        if(province){
            sql += ":province"
            if(city){
                sql += ":city"
                if(area){
                    sql += ":area"
                    if(street){
                        sql += ":street)"
                    }else{
                        sql += ")"
                    }
                }else{
                    sql += ")"
                }
            }else{
                sql += ")"
            }

            let addressResult = await db.sql(sql, {province, city, area, street});
            return addressResult[0].name + address;
        }else{
            return address;
        }
    }


    async validateRealName(realName){
        if(!realName){
            throw new Error("姓名不能为空")
        }
    }


    async validateMobile(mobile){
        if(!mobile){
            throw new Error("手机号不能为空")
        }
        const judgePhone = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
        const st = new RegExp(judgePhone);
        if (!st.test(mobile)) {
            throw new Error("手机号格式不正确")
        }
    }

    async validateOpenId(openId){
        if(!openId){
            throw new Error("OPEN_ID参数缺失")
        }
    }

    async validateCompany(id){
        let company = await this.modules('Company').where({id}).first();
        if(!company){
            throw new Error("公司未匹配")
        }
    }

    async validateIdCard(idCard){
        if(!idCard){
            throw new Error("身份证信息不能为空")
        }
        if(idCard.length !== 18){
            throw new Error("身份证信息不正确")
        }
    }

    async _validateRegion(id){
        let Region = await this.modules('Region').where({id}).first();
        if(!Region){
            throw new Error("未找到该辖区")
        }
    }
}

export default BaseBusinessController;